package com.yenlien.traceyun.business.config;

import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.webase.exception.RestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;

import java.io.IOException;
import java.net.URI;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-03-06
 * @description:restTemplate 异常处理
 **/
public class RestErrorHandler<e> extends DefaultResponseErrorHandler {


    private Logger logger = LoggerFactory.getLogger(RestErrorHandler.class);
    private Object RestException;

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
//        String result = new String(this.getResponseBody(response), Charset.defaultCharset());
        String result = new String(this.getResponseBody(response), CharsetUtil.UTF_8);
        logger.error("调用异常结果:{}", result);
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.containsKey("code") && jsonObject.containsKey("errMsg")) {
                throw new RestException(jsonObject.getString("code"), jsonObject.getString("errMsg"));
            } else {
                throw new RestException("服务调用异常：" + result);
            }
        } catch (Exception e) {
            if (e instanceof RestException) {
                throw e;
            }
            throw new RestException("服务调用catch异常：" + result);
        }

    }

    public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
        logger.error("服务url:{}，调用异常", url);
        this.handleError(response);
    }

}
